package com.rfid.rfidbluetooth.fragment;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.preference.EditTextPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;

import com.rfid.rfidbluetooth.R;
import com.rfid.rfidbluetooth.manager.ToServerManager;

public class SettingFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener{

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.setting, rootKey);
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
        Preference ip = findPreference("ip");
        ip.setSummary(sharedPrefs.getString("ip",ToServerManager.ip));
        EditTextPreference port = findPreference("port");
        String ports = sharedPrefs.getString("port",ToServerManager.port + "");
        port.setSummary(ports + "");
        port.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
            @Override
            public void onBindEditText(@NonNull EditText editText) {
                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("ip") || key.equals("port")) {
            Preference preference = findPreference(key);
            preference.setSummary(sharedPreferences.getString(key,""));
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        ToServerManager.INSTANCE.init();
    }
}
